package com.lhl.jwt.security.handler;

import cn.hutool.json.JSONUtil;
import com.lhl.fw.core.base.ResultDTO;
import com.lhl.jwt.exception.JwtExpiredException;
import com.lhl.jwt.exception.JwtSignatureVerifyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class JwtAuthenticationFailureHandler implements AuthenticationFailureHandler{

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		response.setContentType("Application/json");
		response.setCharacterEncoding("UTF-8");
		response.setStatus(HttpStatus.UNAUTHORIZED.value());
		PrintWriter out = response.getWriter();
		
		if (exception instanceof BadCredentialsException) {
			out.print(JSONUtil.toJsonStr(ResultDTO.builder().succ(false).msg("用户名或密码错误").build()));
		} else if (exception instanceof JwtSignatureVerifyException) {
			out.print(JSONUtil.toJsonStr(ResultDTO.builder().succ(false).msg("token 验证失败").build()));
		} else if (exception instanceof JwtExpiredException) {
			out.print(JSONUtil.toJsonStr(ResultDTO.builder().succ(false).msg("登录过期，请重新登录").build()));
		}
		out.flush();
		log.error(exception.getMessage());
	}	
}
